import { Context } from 'koa';
import { validateDto } from '@/utils/validateDto';
import { CreateArticleDto, UpdateArticleDto, QueryArticleDto, DeleteArticleDto, SelectOneArticleDto } from '@/dto/article.dto';
import articleService from '@/services/article.service';

class ArticleController {
  async selectList(ctx: Context) {

    const reqData = ctx.request.body as QueryArticleDto;
    const errors = await validateDto(QueryArticleDto, reqData);
    if (errors) {
      ctx.body = errors;
      return
    }
    let resData = await articleService.selectList(reqData)
    ctx.body = {
      code: 200,
      message: "列表查询成功",
      data:resData
    };
  }
  async selectOne(ctx: Context) {
    const reqData = ctx.request.body as SelectOneArticleDto;
    let resData = await articleService.selectOne(reqData)

    
    ctx.body = {
      code: 200,
      message:"详情查询成功",
      data: resData,

    };
  }

  async add(ctx: Context) {
    const userId = ctx.state.userId as number;
    const reqData = ctx.request.body as CreateArticleDto;
    reqData.userId = reqData.userId || userId;
    const errors = await validateDto(CreateArticleDto, reqData);
    if (errors) {
      ctx.body = errors;
      return
    }
    const resData = await articleService.add(reqData);   
    
    ctx.body = {
      code: 200,
      message:"添加成功",
      data:{id:resData.id},
    };

  }

  async update(ctx: Context) {
    const reqData = <UpdateArticleDto>ctx.request.body
    const errors = await validateDto(UpdateArticleDto, reqData);
    if (errors) {
      ctx.body = errors;
      return
    }
    const resData = await articleService.update(reqData);   


    ctx.body = {
      code: 200,
      message:"更新成功",
      data: {},
    };

  }
  async delete(ctx: Context) {
    const reqData = ctx.request.body as DeleteArticleDto;
    const errors = await validateDto(DeleteArticleDto, reqData);
    if (errors) {
      ctx.body = errors;
      return
    }
    const resData = await articleService.delete(reqData);

    ctx.body = {
      code: 200,
      message:"删除成功",
      data: {},
    };

  }

}

export default new ArticleController();